package com.wy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wy.common.Result;
import com.wy.entity.SysAdmin;
import com.wy.service.SysAdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * @Author:王渝
 * @Date: 2022/11/30  14:14
 * @Version 1.0
 */
@RestController
@RequestMapping("/admin")
@Slf4j
public class SysAdminController {

    @Autowired
    private SysAdminService sysAdminService;

    /**
     * 管理员登录
     * @param sysAdmin 管理员信息
     * @return
     */
    @RequestMapping("/login")
    public Result<SysAdmin> login(@RequestBody SysAdmin sysAdmin, HttpSession session){
        if(sysAdmin == null){
            return Result.error("用户不存在");
        }
        LambdaQueryWrapper<SysAdmin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(SysAdmin::getAdminId,SysAdmin::getEmployeeName)
                    .eq(SysAdmin::getAccountNumber,sysAdmin.getAccountNumber())
                    .eq(SysAdmin::getPassword, DigestUtils.md5DigestAsHex(sysAdmin.getPassword().getBytes()));
        //select admin_id,employee_name from sys_admin where  account_number = ? and password = ?;
        SysAdmin admin = sysAdminService.getOne(queryWrapper);
        if(admin == null){
            return Result.error("用户名或密码错误");
        }
        //将管理员id存入session
        session.setAttribute("adminId",admin.getAdminId());
        return Result.success(admin);
    }



    @RequestMapping("/logout")
    public Result<SysAdmin> logout(HttpSession session){
        session.removeAttribute("adminId");
        return Result.success(null);
    }
}
